#!/usr/bin/env python

# Author:	Erik Wallentinsen
# Version:	0 (draft)
# Modified:	27/05/2008

class Contact (object):
	def __init__ (self, data):
		self.data 	= data

DB_FILE 	= "contact_data"
DATA_TABLE	= "data"

password = "1234"

from pysqlite2 import dbapi2 as sqlite
from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher
from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher
from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC

connection = sqlite.connect(DB_FILE)
cursor = connection.cursor()
firstRecord = False

def initDatabase():
	cursor.execute('CREATE TABLE ' + DATA_TABLE + ' (id INTEGER PRIMARY KEY, contact_id INTEGER, key BLOB, value BLOB)')
	connection.commit()

def addContact (contact):
	if firstRecord:
		contact.id = 1
		fistRecord = False
	else:
		contact.id = cursor.execute('SELECT MAX(contact_id) FROM ' + DATA_TABLE).fetchall()[0][0] + 1
	connection.commit()
	for key in contact.data:
		addData(contact.id,key,contact.data[key])

def addData (id, key, value):
	cursor.execute('INSERT INTO ' + DATA_TABLE + ' VALUES(null,?,?,?)',(str(id),sqlite.Binary(encrypt(key)),sqlite.Binary(encrypt(value))))
	connection.commit()

def getContact (id):
	set = cursor.execute('SELECT key,value FROM ' + DATA_TABLE + ' WHERE contact_id="' + str(id) + '"')
	data = set.fetchall()
	plain_data = {}
	for key in data:
		if key != None:
			plain_data[decrypt(str(key[0]))] = decrypt(str(key[1]))
	c = Contact(plain_data)
	c.id = id
	return c

def getAllContacts():
	contacts = []
	set = cursor.execute('SELECT DISTINCT contact_id FROM ' + DATA_TABLE)
	for id in set.fetchall():
		contacts.append(getContact(id[0]))
	
	return contacts

def deleteContact (id):
	cursor.execute('DELETE FROM ' + DATA_TABLE + ' WHERE contact_id="' + str(id) + '"')

def encrypt(data):
	encciph = EncryptCipher(password,CIPHER_BLOWFISH,MODE_CBC)
	encciph.feed(data)
	encciph.finish()
	return encciph.data	

def decrypt(data):
	decciph = DecryptCipher(password)
	decciph.feed(data)
	decciph.finish()
	return decciph.data

if len(cursor.execute("SELECT tbl_name FROM sqlite_master WHERE tbl_name = '" + DATA_TABLE + "'").fetchall()) == 0:
	firstRecord = True
	initDatabase()

EncryptCipher()
